<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="选择店铺" prop="storeId">
        <el-select class="width35" v-model="queryParams.storeId" placeholder="请选择店铺"
                   filterable clearable>
          <el-option v-for="(item,index) in autoOperationStoreList" :key="index"
                     :label="item.storeAlias + ' - ' + item.storeName"
                     :value="item.storeId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="店铺别名" prop="storeAlias">
        <el-input v-model="queryParams.storeAlias" placeholder="请输入店铺别名" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="handleAdd">新增店铺</el-button>
      </el-col>
    </el-row>
    <!--  店铺列表  -->
    <el-table v-loading="loading" :data="autoOperationStoreList" border stripe>
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="店铺别名" prop="storeAlias" align="center"/>
      <el-table-column label="店铺名称" prop="storeName" align="center"/>
      <el-table-column label="联系电话" prop="userMobile" align="center"/>
      <el-table-column label="绑定时间" prop="bindTime" align="center"/>
      <el-table-column label="违规" prop="violationScore" align="center" width="100">
        <template slot-scope="scope">
          <span class="borderB changeHand text-blue inlineB" @click="goViolationLog(scope.row)">
            {{ scope.row.violationScore }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="消息数量" prop="msgNumber" align="center" width="100">
        <template slot-scope="scope">
          <el-badge is-dot class="mt10" :hidden="scope.row.msgNumber == '0' ||  !scope.row.msgNumber">
            <div class="borderB changeHand text-blue inlineB" @click="goMessageList(scope.row)">
              {{ scope.row.msgNumber ? scope.row.msgNumber : '0' }}
            </div>
          </el-badge>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.auto_config_status" :value="scope.row.status"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--          <el-button size="mini" type="text" @click="handleViewData(scope.row)">查看数据</el-button>-->
          <el-button size="mini" type="text" @click="handleViewConfig(scope.row)">查看配置</el-button>
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" @click="handleDisable(scope.row)">禁用</el-button>
          <el-button v-if="scope.row.cookieStatus == '1'" size="mini" type="text" class="text-danger"
                     @click="handleCookie(scope.row)">
            提交Cookie
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <el-dialog :title="title" append-to-body :visible.sync="open" width="600px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" size="small">
        <el-form-item label="店铺" prop="storeId">
          <el-select @change="chooseStore" v-model="form.storeId" class="width4" placeholder="请选择店铺"
                     :disabled="form.id" filterable clearable>
            <el-option v-for="(item,index) in storeList" :key="index"
                       :label="item.storeUserName + ' - ' + item.lable"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺别名" prop="storeAlias">
          <el-input v-model="form.storeAlias" disabled></el-input>
        </el-form-item>
        <el-form-item label="店铺名称" prop="storeName">
          <el-input v-model="form.storeName"></el-input>
        </el-form-item>
        <el-form-item label="公司名称" prop="corporateName">
          <el-input v-model="form.corporateName"></el-input>
        </el-form-item>
        <el-form-item label="公司法人" prop="legalPerson">
          <el-input v-model="form.legalPerson"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="userMobile">
          <el-input v-model="form.userMobile" maxlength="11"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="open = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
    <!--  提交cookie弹窗  -->
    <submitCookie v-if="isOpenSubmitCookieModal" @close="closeSubmitCookieModal" :storeId="storeId"
                  :storeUserName="storeUserName"/>
  </div>
</template>

<script>
import configIndex from "@/views/automation/configIndex.vue";
import {
  deleteConfigById,
  saveConfig,
  queryAutoStoreDetail,
  queryAutoStoreList, updateStatusStatus
} from "@/api/autoOperation/autoStore";
import {queryMessageNum} from "@/api/autoOperation/python";
import submitCookie from "@/views/shop/components/SubmitCookie.vue";
import {queryUserShopList} from "@/api/shop";

export default {
  // name: "autoStoreIndex",
  dicts: ['auto_config_status'],
  components: {
    configIndex,
    submitCookie
  },
  data() {
    return {
      loading: false,
      showSearch: true,
      open: false,//是否打开新增配置模态框
      autoConfigValue: "0",
      isOpenConfigIndex: false,//是否打开配置首页组件
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeId: undefined,
        storeAlias: undefined,
        userId: this.$store.getters.userId
      },
      storeList: [],
      autoOperationStoreList: [],//自运营店铺列表
      total: 0,//数据总条数
      form: {},
      rules: {
        storeId: [{required: true, message: "请选择店铺", trigger: "change"}],
        storeName: [{required: true, message: "店铺名称不能为空", trigger: "blur"}],
        storeAlias: [{required: true, message: "店铺别名不能为空", trigger: "blur"}],
        userMobile: [{required: true, trigger: "blur", validator: this.$Validate.isPhone}],
        cookie: [{required: true, message: "cookie不能为空", trigger: "blur"}],
        legalPerson: [{required: true, message: "公司法人不能为空", trigger: "blur"}],
        corporateName: [{required: true, message: "公司名称不能为空", trigger: "blur"}],
      },
      title: "",
      isOpenSubmitCookieModal: false,//是否打开提交cookie弹窗
      storeId: "",
      storeUserName: ""
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
    this.timer = null
  },
  created() {
    this.getList()
    // this.timeTask()
    this.getStoreList()
  },
  methods: {
    // 定时任务
    timeTask() {
      this.timer = setInterval(() => {
        // console.log('定时任务')
        this.getList()
      }, 10000)
      this.$once('hook:beforeDestory', () => {
        clearInterval(this.timer)
      })
    },
    // 选择店铺
    chooseStore(e) {
      console.log('eeee', e)
      if (e) {
        this.form.storeAlias = this.storeList.filter((val, index) => {
          console.log('val', val)
          return val.value == e
        })[0].storeUserName
        console.log('this.form.storeAlias', this.form.storeAlias)
      }
    },
    // 提交cookie
    handleCookie(row) {
      this.storeId = row.storeId;
      this.storeUserName = row.storeAlias
      this.isOpenSubmitCookieModal = true
    },
    // 关闭提交cookie弹窗
    closeSubmitCookieModal() {
      this.isOpenSubmitCookieModal = false
    },
    // 跳转违规记录
    goViolationLog(row) {
      this.$router.push({
        path: "violation/violationLog",
        query: {
          storeId: row.storeId,
        }
      })
    },
    // 跳转消息列表
    goMessageList(row) {
      this.$router.push({
        path: "./messageList",
        query: {
          cookie_str: row.cookie,
        }
      })
    },
    // 获取自动化店铺列表
    getList() {
      this.loading = true
      queryAutoStoreList(this.queryParams).then(res => {
        let data = res.data
        this.total = data.total
        this.getMessageNum(data.list)
      })
    },
    // 获取消息数量
    getMessageNum(list) {
      list.forEach((item) => {
        let data = {
          cookie_str: item.cookie,
          channelId: item.channelId
        }
        queryMessageNum(data).then(res => {
          this.$set(item, "msgNumber", res.data.data.toString())
        }).catch((error) => {
          let {message} = error;
          if (message.substr(message.length - 3) == '503') {
            item.cookieStatus = '1'
            this.$set(item, "cookieStatus", '1')
          }
        })
      })
      this.loading = false
      this.$nextTick(() => {
        this.$forceUpdate() //非必要不使用
        this.autoOperationStoreList = list

      })
    },
    // 禁用
    handleDisable(row) {
      this.$confirm('是否要修改该配置状态？').then(() => {
        updateStatusStatus({id: row.id}).then(res => {
          this.$message.success(res.msg)
          this.getList()
        })
      })
    },
    // 查看数据
    handleViewData(row) {
      this.$router.push({
        path: "./dataDisplay",
        query: {
          storeId: row.storeId,
          id: row.id
        }
      })
    },
    // 查看配置
    handleViewConfig(row) {
      this.$router.push({
        path: "./configIndex",
        query: {
          storeId: row.storeId
        }
      })
      // this.isOpenConfigIndex = true
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      queryAutoStoreDetail({id: row.id}).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改自动化店铺信息";
      });
    },
    // 删除数据
    handleDelete(row) {
      const ids = row.id || this.ids.toString();
      this.$modal.confirm('是否确认删除该用户数据？').then(() => {
        this.loading = true;
        deleteConfigById({id: ids}).then(res => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess(res.msg);
        })
      })
    },
    reset() {
      this.form = {
        id: undefined,
        storeId: undefined,
        storeName: undefined,
        storeAlias: undefined,
        userMobile: undefined,
        bindTime: undefined,
        cookie: undefined,
        legalPerson: undefined,
        corporateName: undefined,
        userId: this.$store.getters.userId,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //  获取店铺列表
    getStoreList() {
      queryUserShopList().then(response => {
        this.storeList = response.data
      })
    },
    handleAdd() {
      this.reset();
      this.title = "新增自动化店铺"
      this.open = true
    },
    dataFormSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          saveConfig(this.form).then(res => {
            this.open = false
            this.getList()
            this.$message.success(res.msg)
          })
        }
      })

    },
    cancel() {
      this.open = false
    },
    close() {
      this.isOpenConfigIndex = false
    }
  }
}
</script>

<style scoped>

</style>
